import * as React from 'react';
import { connect } from 'react-redux';

import { Table, Card, Button, message, Divider, Popconfirm } from 'antd';
import CustomModal from 'components/common/CustomModal';
import CustomPagination from 'components/common/CustomPagination';
import EditForm from './EditForm';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/review';

import { fetchLevelList, createLevel, updateLevel, removeLevel } from 'actions/review';

interface LevelProps {
  dispatch: (action: any) => any;
  loadingGroup: any;
  levels: object[];
  levelTotal: number;
}
interface LevelState {
  editLevel: any;
}

class Index extends React.Component<LevelProps, LevelState> {
  pageInit: number;
  pageSizeInit: number;
  filters: any;

  static defaultProps: LevelProps = {
    dispatch: () => {},
    loadingGroup: {},
    levels: [],
    levelTotal: 0,
  };
  constructor(props: LevelProps) {
    super(props);
    this.state = {
      editLevel: null,
    };

    this.pageInit = 1;
    this.pageSizeInit = 20;
    this.filters = {
      page: this.pageInit,
      pageSize: this.pageSizeInit,
    };
  }

  componentDidMount() {
    this.handleFetchLevels();
  }

  handleFetchLevels = (params: any = {}, isSearch: boolean = false) => {
    this.filters = { ...this.filters, ...params };
    if (isSearch) {
      this.filters.page = this.pageInit;
    }

    this.props.dispatch(fetchLevelList(this.filters));
  };

  showModal = (editLevel: any = 0) => {
    this.setState({
      editLevel,
    });
  };

  hideModal = () => {
    this.setState({
      editLevel: null,
    });
  };

  /**
   * 创建或更新等级
   */
  handleEditorSubmit = (data: Record<string, any>) => {
    const { loadingGroup } = this.props;
    const { editLevel } = this.state;

    const loadingKey = editLevel ? ACTIONS.UPDATE_LEVEL : ACTIONS.CREATE_LEVEL;

    if (isLoading(loadingGroup, loadingKey)) return;

    const action = editLevel ? updateLevel(editLevel.id, data) : createLevel(data);

    this.props.dispatch(action).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        let msg = editLevel ? '修改成功' : '创建成功';
        message.success(msg);

        this.handleFetchLevels();
        this.hideModal();
      }
    });
  };

  handleRemove = (id: number) => {
    const { loadingGroup } = this.props;
    const { editLevel } = this.state;

    if (isLoading(loadingGroup, ACTIONS.REMOVE_LEVEL)) return;

    this.props.dispatch(removeLevel(id)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('删除成功');

        this.handleFetchLevels();
      }
    });
  };

  // 分页回调
  onPageChange = (current: number) => {
    this.handleFetchLevels({ current });
  };

  render() {
    let { loadingGroup, levels, levelTotal } = this.props;
    const { editLevel } = this.state;

    const loadingKey = editLevel ? ACTIONS.UPDATE_LEVEL : ACTIONS.CREATE_LEVEL;

    const paginParams = {
      current: this.filters.page,
      pageSize: this.filters.pageSize,
      total: levelTotal,
      onChange: this.onPageChange,
    };

    const columns = [
      {
        title: '等级',
        dataIndex: 'level',
        render: level => `L${level}`,
      },
      {
        title: '阅读量',
        dataIndex: 'wordCount',
      },
      {
        title: '升级比例(%)',
        dataIndex: 'rate',
      },
      {
        title: '操作',
        render: (text: any, record: any) => (
          <React.Fragment>
            <Button
              icon="edit"
              onClick={e => {
                e.preventDefault();
                this.showModal(record);
              }}>
              编辑
            </Button>
            <Divider type="vertical" key="line" />
            <Popconfirm
              okText="确定"
              cancelText="取消"
              title="你确定要删除此等级吗？"
              onConfirm={e => {
                e.preventDefault();
                this.handleRemove(record.id);
              }}>
              <Button icon="delete" type="danger">
                删除
              </Button>
            </Popconfirm>
          </React.Fragment>
        ),
      },
    ];

    const modalProps = {
      title: editLevel ? '编辑等级' : '新增等级',
      visible: editLevel !== null,
      onCancel: this.hideModal,
      footer: false,
    };

    return (
      <div>
        <Card bordered={false}>
          <Button
            icon="plus"
            type="primary"
            onClick={() => {
              this.showModal();
            }}>
            新建
          </Button>
        </Card>
        <Table
          bordered
          style={{ marginTop: 24 }}
          loading={isLoading(loadingGroup, ACTIONS.FETCH_LEVEL_LIST)}
          size="small"
          rowKey={record => {
            return String(record.id);
          }}
          pagination={false}
          dataSource={levels}
          columns={columns}
        />
        <CustomPagination {...paginParams} />
        <CustomModal {...modalProps}>
          <EditForm
            loading={isLoading(loadingGroup, loadingKey)}
            level={editLevel}
            onSubmit={this.handleEditorSubmit}
          />
        </CustomModal>
      </div>
    );
  }
}

function mapStateToProps(state: any) {
  const { loadingGroup } = state;
  const { levels, levelTotal } = state.review;

  return {
    loadingGroup,
    levels,
    levelTotal,
  };
}

export default connect(mapStateToProps)(Index);
